package service;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import model.AuthorModel;
import model.QuestionModel;
import model.TagModel;

import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import util.SocketContentHandle;
import util.StringHelper;
import util.TagHelper;
import entity.Author;
import entity.Language;
import entity.Question;
import entity.IpSocket;
import entity.Tag;

@SuppressWarnings("unused")
public class ImportUrlThread extends Thread {

	QuestionModel questionModel;
	TagModel tagModel;
	AuthorModel authorModel;
	Date date;
	Document doc;
	String url;
	String socket;

	public ImportUrlThread(String url, String socket) {
		this.url = url;
		this.socket = socket;
	}

	private void processGet() {
		questionModel = new QuestionModel();		
//		try {			
//			doc = util.SocketContentHandle.getSiteContentBySocket(
//					"efreedom.com", "", url, socket);
//			System.out.println("Get content with ip : " + socket);
//		} catch (UnknownHostException ex) {
//			System.out
//					.println("UnknownHostException occur when get question url");
//		} catch (IOException ex) {
//			System.out.println("IOException occur when get question url");
//		}
//
//		String title = doc.select("#questionTitle").text();
//		String question = doc.select("#fullQuestionBody").html();
//		String answer = doc.select("#fullAnswerBody").html();
//		String answerAuthor = doc.select("#hypAnswerAuthor").text();
//		String questionAuthor = doc.select("#hypQuestionAuthor").text();

		Question obj = new Question();
		obj.setUrl(url);
//		obj.setTitle(title);
//		obj.setAlias(StringHelper.replace(title));
//
//		obj = addTags(obj);
//		obj = addOtherTags(obj);
//		obj = addQuestionAuthor(obj, questionAuthor);
//		obj = addAnswerAuthor(obj, answerAuthor);
//		obj.setContent(question);

		date = new Date();
		obj.setLastUpdateDate(date);
		obj.setDoc(date);

//		obj.setContentAnswer(answer);
//		obj.setHadContent(1);
//		obj.setLang("en");
//		if (obj.isValid()) {
//			questionModel.add(obj);
//			addLanguages(obj);
//			System.out.println("Import surccess !");
//			System.out.println("Adding 34 language... with multy thread !");
//		} else {
//			System.out.println("Question's invalid !");
//		}
		obj.setHadContent(0);
		obj.setLang(null);
		questionModel.save(obj);
		System.out.println("Add url success !");
		Thread.currentThread().interrupt();

	}

	private Question addAnswerAuthor(Question obj, String answerAuthor) {
		String aliasAnswer = StringHelper.replace(answerAuthor);
		authorModel = new AuthorModel();
		Author ans = authorModel.findByAlias(aliasAnswer);
		if (ans.getAlias() != null && !ans.getAlias().equals("")) {
			ans.setCountAnswer(ans.getCountAnswer() + 1);
			authorModel.save(ans);
		} else {
			int randomAvatar = 1 + (int) (Math.random() * 33);
			Author a = new Author();
			a.setAvatar("author" + randomAvatar + ".png");
			a.setName(answerAuthor);
			a.setAlias(aliasAnswer);
			a.setCountAnswer(1);
			a.setCountQuestion(0);
			authorModel.save(a);
		}
		obj.setAliasAuthorAnswer(aliasAnswer);
		return obj;
	}

	private Question addQuestionAuthor(Question obj, String questionAuthor) {
		String aliasAuthor = StringHelper.replace(questionAuthor);
		authorModel = new AuthorModel();
		Author ask = authorModel.findByAlias(aliasAuthor);
		if (ask.getAlias() != null && !ask.getAlias().equals("")) {
			int curr = ask.getCountQuestion();
			ask.setCountQuestion(curr + 1);
			authorModel.save(ask);
		} else {
			int randomAvatar = 1 + (int) (Math.random() * 33);
			Author author = new Author();
			author.setAvatar("author" + randomAvatar + ".png");
			author.setName(questionAuthor);
			author.setAlias(aliasAuthor);
			author.setCountAnswer(0);
			author.setCountQuestion(1);
			authorModel.save(author);
		}
		obj.setAliasAuthor(aliasAuthor);
		return obj;
	}

	private Question addTags(Question obj) {

		Elements tags = doc.select(".topicBoxSmall");
		// Tag handle, get all tag name from original
		ArrayList<String> temp = new ArrayList<String>();
		if (tags.size() > 0) {
			for (int i = 0; i < tags.size(); i++) {
				String value = tags.get(i).text().toLowerCase();
				temp.add(value);
			}
		}
		// from o2tv
		doc = TagHelper.help(doc);
		Elements myTags = doc.select(".tag");

		if (myTags.size() > 0) {
			for (int i = 0; i < myTags.size(); i++) {
				String value = myTags.get(i).text().toLowerCase();
				if (!temp.contains(value)) {
					temp.add(value);
				}
			}
		}
		int tempSize = 0;
		if (temp.size() > 30) {
			tempSize = 30;
		} else {
			tempSize = temp.size();
		}
		tagModel = new TagModel();
		if (temp.size() > 0) {
			for (int i = 0; i < tempSize; i++) {
				if (!temp.get(i).equals("m") && !temp.get(i).equals("t")) {

					String aliasTag = StringHelper.tag(temp.get(i));
					obj.getTags().add(aliasTag);

					Tag had = tagModel.find(aliasTag);
					if (had.getAlias() != null && !had.getAlias().equals("")) {
						had.setCount(had.getCount() + 1);
						tagModel.save(had);
					} else {
						Tag tag = new Tag();
						tag.setName(temp.get(i));
						tag.setAlias(aliasTag);
						tag.setCount(1);
						tagModel.save(tag);
					}
				}
			}
		}
		return obj;
	}

	private Question addOtherTags(Question obj) {
		tagModel = new TagModel();
		while (obj.getOtherTags().size() <= 30) {
			boolean had = false;
			Tag random = tagModel.random();
			for (String tag : obj.getTags()) {
				if (tag.equals(random.getAlias())) {
					had = true;
				}
			}
			if (!had) {
				obj.getOtherTags().add(random.getAlias());
			}
		}
		return obj;
	}

	private void addLanguages(Question obj) {
		IpSocket mySocket = new IpSocket();
		Language language = new Language();
		for (String lang : language.listLang) {
			new GetLanguageThread(obj, lang, mySocket.get());
		}
	}

	private boolean hadContent(Question obj) {
		if (obj.getContent() == null || obj.getContent().equals("")) {
			return false;
		}
		if (obj.getTitle() == null || obj.getTitle().equals("")) {
			return false;
		}
		return true;
	}

	public void run() {
		questionModel = new QuestionModel();
		if (!questionModel.isGotten(url)) {
			processGet();
		} else {
			System.out.println("This question's gotten baby !");
		}
		System.out.println("Finish insert content ! ");
	}
}
